import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from settings import send_to_email
from email.mime.image import MIMEImage
from utils import capture_screenshot

# 全局变量，配置发件人、SMTP 服务器、邮件主题和内容等信息
SENDER_EMAIL = "service@mailbox.hongfund.com"
SENDER_PASSWORD = "ServicePwd748541985"
SMTP_SERVER = "smtpdm.aliyun.com"
SMTP_PORT = 80
SUBJECT = "手撕万象，出货了！！！！！"
MESSAGE = "手撕万象，出货了！！！！！"


def send_notification_email():
    """
    发送通知邮件的函数
    :param recipient_email: 单个收件人邮箱地址
    """
    if send_to_email is None:
        return
    msg = MIMEMultipart()
    msg['Subject'] = SUBJECT
    msg['From'] = SENDER_EMAIL
    msg['To'] = send_to_email

    # 创建 HTML 内容并引用图片
    html_content = f"""
    <html>
        <body>
            <p>{MESSAGE}</p>
            <img src="cid:image1">
        </body>
    </html>
    """
    msg.attach(MIMEText(html_content, 'html'))

    try:
        # 调用截图函数
        screenshot = capture_screenshot()
        if screenshot is not None:
            import cv2
            import io
            # 将 OpenCV 图像转换为字节流
            is_success, buffer = cv2.imencode('.png', screenshot)
            io_buf = io.BytesIO(buffer)

            # 创建 MIMEImage 对象
            img = MIMEImage(io_buf.getvalue())
            # 设置图片的 Content-ID
            img.add_header('Content-ID', '<image1>')
            msg.attach(img)
        else:
            print("截图失败，未添加图片到邮件内容。")

        with smtplib.SMTP(SMTP_SERVER, SMTP_PORT) as server:
            server.starttls()
            server.login(SENDER_EMAIL, SENDER_PASSWORD)
            server.sendmail(SENDER_EMAIL, [send_to_email], msg.as_string())
        print("邮件发送成功！")
    except smtplib.SMTPException as e:
        print(f"邮件发送失败: {e}")
    except Exception as e:
        print(f"发生未知错误: {e}")


if __name__ == "__main__":
    send_notification_email()
